<?php
/**
 * Created by PhpStorm.
 * User: clcw908
 * Date: 2017/1/10
 * Time: 15:53
 */
date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
	die('error');
}

if (!defined('API_ROOT_PATH')) {
	define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
	$db = new MysqliDb ([
		'host' => MYSQLDB,
		'username' => MYSQLDB_USER,
		'password' => MYSQLDB_PWD,
		'db' => MYSQLDB_DATABASE,
		'port' => 3306,
		'prefix' => 'au_',
		'charset' => 'utf8'
	]);
	return $db;
}
$db = init_db();

$bc_id = 0;
$lastId = 0;

$list = $db->rawQuery('select * from au_breach_car where car_id = order_id');
//$list = $db->where('car_id',`order_id`)->get('breach_car',2000);
if(empty($list)){
	logUtil('处理完成');die();
}

foreach ($list as $key=>$value){
	$carId = $value['car_id'];
	$bcId = $value['bc_id'];
	$breachCarCreateTime = $value['create_time']; //违约车辆创建时间
	$orderInfo = $db->where('car_id',$carId)->get('order');
	if(!empty($orderInfo)){
		if(count($orderInfo) > 1){
			$orderInfo = $db->where('create_time',$breachCarCreateTime,'<')->where('car_id',$carId)->orderBy('create_time')->getOne('order');
			if(empty($orderInfo)){
				print_r($db->getLastQuery());die();
			}
		}else{
			$orderInfo = $orderInfo[0];
		}

		$orderId = $orderInfo['order_id'];
		$data = [
			'order_id' => $orderId,
		];
		$result = true;
		$result = $db->where('bc_id',$bcId)->update('breach_car',$data);
		if(!$result){
			logUtil('违约车辆:'.$bcId.'更新拍单号失败！');die();
		}else{
			logUtil('违约车辆:'.$bcId.'更新拍单号成功！');
		}
	}
}